<?php

declare(strict_types=1);

namespace app\backend\controller\crm;

use app\common\controller\Basic;
use app\common\service\sys\ConfigService;

/**
 * 客户跟进记录 控制器
 * @author 吕玉冰
 * @date  2022-07-22
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class Set extends Basic
{

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        // 当前控制器服务实例化
        $this->service = new ConfigService();
    }

    /**
     * 列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $data = rq_decode(input('param.'));
            if (!isset($data['crm_no_record'])) {
                $data['crm_no_record'] = '0';
            }
            if (!isset($data['crm_sign_record'])) {
                $data['crm_sign_record'] = '0';
            }
            if (!isset($data['crm_no_deal'])) {
                $data['crm_no_deal'] = '0';
            }
            $saveData = [];
            foreach ($data as $key => $value) {
                $temp = [];
                $temp['name'] = $key;
                $temp['value'] = $value;
                $saveData[$key] = $temp;
            }
            $allow_key = ["crm_qq_map_key", "crm_is_stmp"
                , "crm_smtp_host", "crm_smtp_username"
                , "crm_smtp_password", "crm_smtp_port"
                , "crm_is_thinkapi_message", "crm_thinkapi_message_appcode"
                , "crm_thinkapi_message_sign", "crm_no_record"
                , "crm_sign_record", "crm_sign_record_day"
                , "crm_no_deal", "crm_no_deal_days"
            ];
            foreach ($saveData as $key => $value) {
                $key = $value['name'];
                if (in_array($key, $allow_key)) {
                    $where = [];
                    $where[] = ["name", '=', $key];
                    if ($this->service->getTotal($where) == 0) {
                        $this->service->add($value);
                    } else {
                        $info = $this->service->getInfoByWhere($where);
                        $this->service->update($info->id, $value);
                    }
                }
            }
            return _ok('ok', $data);
        } else {
            $data = [];
            $where = [];
            $where[] = ["name", "like", "crm_%"];
            $list = $this->service->getListAll($where, false);
            foreach ($list as $key => $value) {
                $data[$value['name']] = $value['value'];
            }
            return _ok('ok', $data);
        }
    }

}
